const puppeteer = require('puppeteer')
const url = 'https://passport.csdn.net/login'
const sleep = time => new Promise(resolve => {
    setTimeout(resolve, time)
})

function asyncOn(target,e,cb){
    return new Promise(resolve=>{
        target.on(e,()=>{
            cb()
            resolve()
        })
    })
}
    ;(async () => {
        console.log('Start visit this target page')
        const browser = await puppeteer.launch({
            args: ["--no-sandbox"],
            dumpio: false
        })
        const page = await browser.newPage()
        await page.goto(url, {
            waitUntil: 'networkidle2'
        })
        // page.on('pageerror', msg => {
        //     console.log(msg)
        // })
        // page.on('load', msg => {
        //     console.log('load', msg)
        // })
        await sleep(1000)
        console.log('wati1 start')


        await page.waitForSelector('.main-select ul li:nth-child(2)')
        for (i = 0; i < 1; i++) {
            await sleep(1000)
            await page.click('.main-select ul li:nth-child(2)')
        }

        console.log('wati1 end')

        await sleep(1000)

        console.log('wati2 start')
        await page.waitForSelector('.form-group input#all')
        for (i = 0; i < 1; i++) {
            await sleep(1000)
            await page.type('.form-group input#all', 'JCY1009015337')
        }
        console.log('wati2 end')

        console.log('type1 start')
        await page.waitForSelector('.form-group input#password-number')
        for (i = 0; i < 1; i++) {
            await sleep(1000)
            await page.type('.form-group input#password-number', ' jcy199206284716')
        }
        console.log('type1 end')

        console.log('click start')

        await page.waitForSelector('.form-submit button')
        for (i = 0; i < 1; i++) {
            await sleep(1000)
            await page.click('.form-submit button')
        }

        console.log('click end')
        // await page.waitForSelector('.phr_second')

        // await sleep(3000)

        await asyncOn(page,'load',()=>{
            console.log('async loaded')
        })
        // await page.waitForSelector('.phr_second')
        await sleep(1000)
        const result = await page.evaluate(() => {
            // console.log('122')
            console.log(document.body.innerText)
            // let $ = window.$
            // let it = $('div')[0]
            // console.log(it)
            return document.body.innerText
        })

        browser.close()
        process.send(result)
        process.exit(0)
    })()